import os

from django import forms
from django.core.paginator import Paginator, EmptyPage
from django.db import transaction
from django.http import Http404, HttpResponse
from django.shortcuts import render, redirect

# Create your views here.
from django.views.generic import ListView

import account
from account.forms import LoginForm, UserEditForm, UserRegForm, UserChangeForm, AvatarUploadForm
from account.models import User, UserProfile
from my_project import settings


def user_info(request):
    """用户详情-查询优化"""
    user = User.objects.get(pk=1)
    profile_list = UserProfile.objects.all().select_related('user')
    user_list = User.objects.raw('SELECT *FROM account_user ')
    return render(request, 'user_info.html', {
        'user': user,
        'profile_list': profile_list,
        'user_list': user_list
    })


def user_list_slice(request):
    # try
    # except
    """分页-使用切片"""
    page = request.GET.get('page', 1)
    page = int(page)
    # 每页放多少条数据
    page_size = 10
    start = (page - 1) * page_size
    end = page * page_size
    user_list = User.objects.all()[start:end]
    return render(request, 'user_list_slice.html', {
        'user_list': user_list,
    })


def user_list_paginator(request):
    # 利用分页器进行分页
    page = request.GET.get('page', '')
    print(page)
    user_list = User.objects.all()
    # 第一步,取得分页器
    p = Paginator(user_list, 15)
    # 第二步，取得某一页的对象（实例）
    try:
        page_data = p.get_page(page)
    except EmptyPage as e:
        raise Http404
    return render(request, 'user_list_paginator.html', {
        'page_data': page_data
    })


class UserListView(ListView):
    """分页处理 面向对象"""
    template_name = 'user_list_class.html'
    model = User
    paginate_by = 20
    page_kwarg = 'p'


def user_register(request):
    """用户注册"""
    # 1.获取表单信息
    # 2.验证数据是否符合要求
    # 3.添加用户信息（用户基本信息，详细信息）
    try:
        user = User.objects.create(username='102',
                                   password='123456',
                                   nickname='王五')
        profile = UserProfile.objects.create(user=user, usernamex='102')
        # 4.反馈信息：成功/失败
        return HttpResponse('ok')
    except Exception as e:
        user.delete()
        print(e)
        return HttpResponse('no')


@transaction.atomic()
def user_signup_trans(request):
    """事物的使用-装饰器"""
    user = User.objects.create(username='103',
                               password='123456',
                               nickname='王五')
    profile = UserProfile.objects.create(user=user, usernamex='102')
    return HttpResponse('ok')


def user_signup_trans_with(request):
    """事物-with"""
    with transaction.atomic():
        user = User.objects.create(username='104',
                                   password='123456',
                                   nickname='王五')
        profile = UserProfile.objects.create(user=user, username='104')
    return HttpResponse('ok')


# @transaction.atomic()
def user_signup_trans_hand(request):
    """事物的自动提交"""
    # 放弃自动提交事物
    transaction.set_autocommit(False)
    try:
        user = User.objects.create(username='107',
                                   password='123456',
                                   nickname='王五')
        profile = UserProfile.objects.create(user=user, username='107')
        # 手动提交事物
        transaction.commit()
        # 4.反馈信息：成功/失败
        return HttpResponse('ok')
    except Exception as e:
        # user.delete()
        print(e)
        # 手动控制事物，实现回滚
        transaction.rollback()
        return HttpResponse('no')


def user_login(request):
    """用户登录"""
    form = LoginForm()
    if request.method=='POST':
        form=LoginForm(request.POST)
        if form.is_valid():
            print('表单验证通过')
        else:
            print(form.errors)
    else:
        form = LoginForm()
    return render(request, 'user_login.html', {
        'form': form
    })


def user_edit(request):
    """用户信息维护"""
    if request.method == 'POST':
        form = UserEditForm(data=request.POST)
        if form.is_valid():
            print('表单通过验证')
    else:
        form = UserEditForm()
    return render(request, 'user_edit.html', {
        'form': form
    })

def user_reg(request):
    """用户注册"""
    if request.method == 'POST':
        data=request.POST
        print(data)
        form = UserRegForm(data=request.POST,files=request.FILES)
        #是否已经通过验证
        if form.is_valid():
            form_data=form.cleaned_data
            print('验证通过后的数据：',form_data)
        else:
            print(form.errors.as_json)
    else:
        #表单初始化的数据
        initial_data={
            'nickname':'默认昵称',
        }
        form = UserRegForm(initial=initial_data)
    return render(request,'user_reg.html',{
        'form':form
    })

def user_change(request):
    """用户信息维护"""
    if request.method == 'POST':
        form = UserChangeForm(data=request.POST,files=request.FILES)
        if form.is_valid():
            data=form.cleaned_data
            form.save()
            print('表单通过验证')
            return redirect('/')
    else:
        form = UserChangeForm()
    return render(request, 'user_change.html', {
        'form': form
    })

def upload_user_form(request):
    """文件上传-表单上传"""
    if request.method=='POST':
        file=request.FILES.get('avatar',None)
        if file:
            filename=os.path.join(settings.MEDIA_ROOT,'test.jpg')
            with open(filename,'wb+') as dest:
                for chunk in file.chunks():
                    dest.write(chunk)
            print('文件上传成功')
    return render(request,'upload_user_form.html')


def upload_user_form2(request):
    """文件上传-表单上传"""
    if request.method=='POST':
        form=AvatarUploadForm(data=request.POST,files=request.FILES)
        if form.is_valid():
            file=form.cleaned_data['avatar']
        file=request.FILES.get('avatar',None)
        if file:
            filename=os.path.join(settings.MEDIA_ROOT,'avatar.jpg')
            with open(filename,'wb+') as dest:
                for chunk in file.chunks():
                    dest.write(chunk)
            print('文件上传成功')
    else:
        form=AvatarUploadForm()
    return render(request,'upload_user_form2.html',{
        'form':form
    })

